package be.ipl.diavoloz.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import be.ipl.diavoloz.modele.Partie;
import be.ipl.diavoloz.usecases.GestionPartie;

/**
 * Servlet implementation class ListerPartie
 */
@WebServlet("/lister.html")
public class ListerPartie extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@EJB
	private GestionPartie gestionPart;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ListerPartie() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		final ServletContext ctx = getServletContext();
		synchronized (ctx) {
			if (request.getSession().getAttribute("connected").equals(true)) {
				//test
//				System.out.println(request.getSession().getAttribute("nameConn"));
//				gestionPart.creerUnePartie((String) request.getSession()
//						.getAttribute("nameConn"), "test1");
				List<Partie> listeParties = gestionPart.listerPartiesEnAttente();
				ctx.setAttribute("listeParties", listeParties);
				System.out.println(" nb de parties " + listeParties.size());
				ctx.getNamedDispatcher("liste.html").forward(
						request, response);
			} else {
				ctx.getNamedDispatcher("index.html").forward(
						request, response);
			}
		}
		
	}

}
